from fastapi import APIRouter, Request
from fastapi import Depends
from config.get_db import get_db
from module_admin.entity.vo.cms_order_approve_vo import OrderModelForApprove
from module_admin.entity.vo.cms_order_dispatch_vo import OrderDispatchModelForCreate, OrderModelForDispatchDriver, \
    OrderDetailsForDriver, OrderDetailsForDriverQuery
from module_admin.entity.vo.cms_order_vo import OrderModel, OrderPageObject, OrderModelForQuery, OrderModelForPage
from module_admin.entity.vo.user_vo import CasdoorUser
from module_admin.service.cms_order_dispatch_service import CmsOrderDispatchService
from module_admin.service.cms_order_service import CmsOrderService
from module_admin.dao.dept_dao import *
from module_admin.service.login_service import get_current_user_details
from utils.page_util import get_page_obj, get_new_page_obj
from utils.response_util import *
from utils.log_util import *

driverTaskController = APIRouter(dependencies=[Depends(get_current_user_details)])


@driverTaskController.post("/task/changeState",
                           summary="待办任务-任务确认(退回-确认-开始任务-完结)")
async def change_state(request: Request, driver_query: OrderModelForDispatchDriver,
                       query_db: Session = Depends(get_db),
                       current_user: CasdoorUser = Depends(get_current_user_details)):
    try:
        dept_query_result = CmsOrderDispatchService.driver_operate(query_db, driver_query, current_user)
        return response_200(data=dept_query_result, message="操作成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@driverTaskController.post("/task/confirmDetail", response_model=OrderDetailsForDriver,
                           summary="待办任务-（任务确认，任务开始，任务结束）详情")
async def confirm_detail(request: Request, query: OrderDetailsForDriverQuery,
                         query_db: Session = Depends(get_db)):
    try:
        dept_query_result = CmsOrderDispatchService.detail(query_db, query)
        return response_200(data=dept_query_result, message="获取成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@driverTaskController.post("/task/pageForDriver", response_model=OrderModelForPage, summary="全部记录(针对驾驶员)")
async def page_order_driver(request: Request, order_page_query: OrderPageObject, db: Session = Depends(get_db)):
    try:
        # query_object = OrderModelForQuery(**order_page_query.dict())
        page_result = CmsOrderService.page2(db, order_page_query)
        total = CmsOrderService.count2(db, order_page_query)
        list_format_datetime(page_result)
        # 分页操作
        page_result_after = get_new_page_obj(page_result, order_page_query.page_num, order_page_query.page_size, total)
        # 处理
        return response_200(data=page_result_after, message="获得成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))
